package com.mulanweb.api.module.controller.seller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.utils.DateUtil;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;
import org.jsoup.helper.StringUtil;

import java.util.*;

/**
 * Created by Administrator on 2016/8/19.
 */
@ValidateFile
public class SellerContentController extends BaseController {

    @ValidateForm
    public void search() {
        Long sellerId = getSessionAttr("sellerId");
        Integer typeId = getParaToInt("typeId");
        SQLGenerateHelper helper = null;
        if(typeId==23){
            helper = new SQLGenerateHelper("ticket","create_time desc");
        }else if(typeId ==24){
            helper = new SQLGenerateHelper("chartered","create_time desc");
        }else{
            returnFailureJson();
            return;
        }
        helper.addEqualsCondition("seller_id",sellerId);
        helper.addIsNullCondition("delete_time");

        if(typeId==23){
            Page<Ticket> page = Ticket.dao.paginate(getPageNumber(),getPageSize(),helper.getSqlSelect(),helper.getSqlExceptSelect(), helper.getQueryParas());
            returnPageModelJson(page);
        }else if(typeId ==24){
            Page<Chartered> page = Chartered.dao.paginate(getPageNumber(),getPageSize(),helper.getSqlSelect(),helper.getSqlExceptSelect(), helper.getQueryParas());
            Map<String,Object> map = new HashMap<String,Object>();
            List<Map> list = new ArrayList<>();
            for(Chartered chartered : page.getList()){
                Map<String,Object> contentMap = new HashMap<String,Object>();
                List<DriverJoinSt> djs = DriverJoinSt.dao.find("SELECT * FROM driver_join_st WHERE chartered_id=? AND driver_id=?",chartered.getId(),chartered.getSellerId());
                List<Integer> serverWeek= new ArrayList<>();
                for(DriverJoinSt dd : djs){
                    serverWeek.add(dd.getServiceTimeId());
                }
                contentMap.put("target",chartered);
                contentMap.put("weekWork", StringUtil.join(serverWeek,","));
                list.add(contentMap);

            }
            map.put("DataList",list);
            map.put("TotalRow",page.getTotalRow());
            map.put("PageNumber",page.getPageNumber());
            map.put("PageSize",page.getPageSize());
            map.put("TotalPage",page.getTotalPage());
            map.put("ReturnCode",1);

            renderJson(map);
        }
    }

    @ValidateForm
    public void updateStatus(){
        Integer typeId = getParaToInt("typeId");
        Long targetId = getParaToLong("targetId");
        if(typeId == 23){
            Ticket ticket = Ticket.dao.findById(targetId);
            if(ticket.getNotAvailableTime() !=null){
                ticket.setNotAvailableTime(null);
            }else{
                ticket.setNotAvailableTime(new Date());
            }
            if(ticket.update()){
                returnSuccessJson();
            }else{
                returnFailureJson();
            }
        }else if(typeId == 24){
            Chartered chartered =Chartered.dao.findById(targetId);
            if(chartered.getNotAvailableTime() !=null){
                chartered.setNotAvailableTime(null);
            }else{
                chartered.setNotAvailableTime(new Date());
            }
            if(chartered.update()){
                returnSuccessJson();
            }else{
                returnFailureJson();
            }
        }
    }

    @ValidateForm
    public void updateTicket(){
        Long ticketId = getParaToLong("targetId");
        Integer surplus = getParaToInt("amount");
        Ticket ticket = Ticket.dao.findById(ticketId);
        if(StrKit.notNull(ticket) && ticket.getDeleteTime() == null && ticket.getNotAvailableTime() == null){
            if(surplus >=0){
                ticket.setTotal(ticket.getTotal() - (ticket.getSurplusTotal() - surplus));
                ticket.setSurplusTotal(surplus);
                if(ticket.update()){
                    returnSuccessJson();
                }else{
                    returnFailureJson();
                }
            }else{
                returnJson(0,"不能少于0");
            }
        }else{
            returnJson(0,"对象可能(不存在,已下架,已被管理员删除)！");
        }
    }

    @ValidateForm
    public void updateChartered(){
        String weekWork = getPara("weekWork");
        String startTime = getPara("startTime");
        String endTime = getPara("endTime");
        Long charteredId = getParaToLong("targetId");
        Chartered chartered = Chartered.dao.findById(charteredId);
        if(StrKit.notNull(chartered)){
            chartered.setStartTime(DateUtil.strToDate(startTime,"hh:mm"));
            chartered.setEndTime(DateUtil.strToDate(endTime,"hh:mm"));
            List<DriverJoinSt> driverJoinSts = DriverJoinSt.dao.find("SELECT * FROM driver_join_st WHERE chartered_id = ? AND driver_id=?",charteredId,chartered.getSellerId());
            int deleteCount = 0 ;
            for(DriverJoinSt st : driverJoinSts){
                st.delete();
                deleteCount++;
            }
            String[] weekWorks = weekWork.split(",");
            int saveCount = 0 ;
            for(String tt : weekWorks){
                DriverJoinSt st = new DriverJoinSt();
                st.setCharteredId(chartered.getId());
                st.setServiceTimeId(Integer.parseInt(tt));
                st.setDriverId(chartered.getSellerId());
                st.setCreateTime(new Date());
                st.save();
                saveCount++;
            }
            if(deleteCount==driverJoinSts.size() && saveCount==weekWorks.length && chartered.update()){
                returnSuccessJson();
            }else{
                returnFailureJson();
            }
        }
    }

    @ValidateForm
    public void getOrder(){
        Long sellerId = super.getSessionAttr("sellerId");
        Seller seller = Seller.dao.findById(sellerId);
        if(seller != null){
            SQLGenerateHelper helper = new SQLGenerateHelper("`order`","create_time");
            helper.addEqualsCondition("seller_id",sellerId);
            Page<Order> page  = Order.dao.paginate(getPageNumber(),getPageSize(),helper.getSqlSelect(),helper.getSqlExceptSelect(),helper.getQueryParas());
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("rows",page.getList());
            map.put("ReturnCode",1);
            map.put("PageSize",page.getPageSize());
            map.put("PageNumber",page.getPageNumber());
            map.put("TotalPage",page.getTotalPage());
            map.put("TotalRow",page.getTotalPage());
            renderJson(map);
        }
    }
}
